package edu.indiana.d2i.vmm.http;

import java.io.IOException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;

public class HTRCHttpServer {
	protected Server webServer;
	protected Connector listener;
	protected WebAppContext webAppContext;
	
	public static final Log LOG = LogFactory.getLog(HTRCHttpServer.class);
	
	protected String getWebAppsPath() throws IOException {
	    URL url = getClass().getClassLoader().getResource("webapps");
	    if (url == null) 
	      throw new IOException("webapps not found in CLASSPATH"); 
	    return url.toString();
	}
	
	protected Connector createBaseListener()
    throws IOException {
		SelectChannelConnector ret = new SelectChannelConnector();
		ret.setLowResourceMaxIdleTime(10000);
		ret.setAcceptQueueSize(128);
		ret.setResolveNames(false);
	    ret.setUseDirectBuffers(false);
		return ret;
	}
	
	public HTRCHttpServer(String name, String bindAddress, int port) throws IOException {
		webServer = new Server();
		
	    listener = createBaseListener();
	    listener.setHost(bindAddress);
	    listener.setPort(port);
	    webServer.addConnector(listener);
	    
	    final String appDir = getWebAppsPath();
//	    String appDir = "../build/webapps";
	    LOG.info("appDir " + appDir);
	    webAppContext = new WebAppContext();
	    
//	    webAppContext.setDescriptor(appDir + "/webapps/" + name + "/WEB-INF/web.xml");
//	    webAppContext.setContextPath("/");
//	    webAppContext.setResourceBase("./build/classes/edu/indiana/d2i/vm");
//	    webAppContext.setParentLoaderPriority(true);
        
	    webAppContext.setContextPath("/");
	    webAppContext.setWar(appDir + "/" + name);
	    webServer.addHandler(webAppContext);
	}
	
	public void setAttribute(String name, Object value) {
		webAppContext.setAttribute(name, value);
	}
	
	public void start() throws Exception {
		webServer.start();
	}
	
	public void join() throws InterruptedException {
		webServer.join();
	}
	
	public void stop() {
		
	}
}
